package com.tyut.musicdreamer.service.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR;

/**
 * 路由日志过滤器
 * 记录请求的路由信息，帮助调试
 */
@Component
@Slf4j
public class RouteLoggingFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().toString();
        String method = request.getMethod().toString();
        
        // 获取路由信息
        Route route = exchange.getAttribute(GATEWAY_ROUTE_ATTR);
        if (route != null) {
            String routeId = route.getId();
            String routeUri = route.getUri().toString();
            log.info("请求路由信息: 方法={}, 路径={}, 路由ID={}, 目标URI={}", 
                    method, path, routeId, routeUri);
        } else {
            log.info("请求未匹配到路由: 方法={}, 路径={}", method, path);
        }
        
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        // 在HeaderCleanupFilter之后执行
        return -180;
    }
} 